package com.mk.episodecalendar.activities;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.mk.episodecalendar.Global;
import com.mk.episodecalendar.R;
import com.mk.episodecalendar.security.AuthResult;

public class Login extends Activity 
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        if(Global.CurrentUser != null && Global.CurrentUser.getIsAuthenticated())
        {
        	finish();
        }
        else
        {
	        Button next = (Button) findViewById(R.id.Button01);
	        next.setOnClickListener(new View.OnClickListener() {
	            public void onClick(View view) {
	            	
	            	String userName = ((EditText)findViewById(R.id.EditText01)).getText().toString().trim(); 
	            	String password = ((EditText)findViewById(R.id.EditText02)).getText().toString().trim();
	            	CheckBox autoLogin = (CheckBox)findViewById(R.id.CheckBox01);
	            	
	            	AuthResult loginResult = Global.AuthModule.Login(userName, password);
	            	if(loginResult.getSuccess())
	            	{
	            		Global.setCurrentUser(userName, true);
	            		
	            		Global.ApplicationPrecferences.setAutoLogin(autoLogin.isChecked());
	            		Global.ApplicationPrecferences.setUserName(userName);
	            		Global.ApplicationPrecferences.setAuthKey(loginResult.getAuthKey());
						
	            		finish();
	            	}
	            	else
	            	{
	            		Toast toast = Toast.makeText(view.getContext(), "Login failed..", 2000);
	            		toast.show();
	            	}
	            }
	        });
	        
	        TextView createAccountLink = (TextView)findViewById(R.id.TextView03);
	        
	        createAccountLink.setOnClickListener(new OnClickListener() {
				
				public void onClick(View v) {
					Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse(getResources().getString(R.string.create_account_link_url)));
			        startActivity(browserIntent);
				}
			});
        }
    }
}